<?php

/**
 * 前台关于积分商品的操作
 * 用户关于积分操作
 * 可通过积分购买商品，可添加积分商品
 */
class RedeemgoodController extends UserLoginBaseC {

    public function init() {
        parent::init();
        if (yii::app()->user->kind == 1) {
            $this->error('商家用户才可进行此操作', '/user/info');
        }
    }

    /**
     * 商家用户添加积分商品
     * @return [type] [description]
     */
    public function actionAdd() {
        $this->error('该功能已关闭');
        $objModel = new RedeemModel('add');
        $objModel->resetAttributes();
        $objModel->scoregood_intervals = 30; //默认半个小时
        if (isset($_POST['RedeemModel'])) {

            $objMember = MembersModel::model()->findByPk(yii::app()->user->id);
            if(empty($objMember->phone))
            {
                 $this->error('请绑定手机后再报名！', self::U('info/index'));
            }
            //判断是否绑定旺旺
            $memberTB = MembersTaobaoModel::model()->getMemberTB(Yii::app()->user->id);
            if (empty($memberTB->taobao_user_nick) && $_POST['item_type'] != 11) {
                $this->error('请绑定旺旺后再报名！', self::U('info/aliwang'));
            }
            //过滤Post数据
            $this->unsetPostData(array('status', 'admin_id', 'pay_status'));

            //增加POST数据
            $_POST['RedeemModel']['uid'] = yii::app()->user->id;
            $_POST['RedeemModel']['frequency'] = 1;
            //获取所有的会员组，默认所有的用户组都选
            $_POST['RedeemModel']['member_group'] = implode(',', array_keys(MembersGroupModel::model()->getGroupArr()));
            $_POST['RedeemModel']['introduction'] = CHtml::encode($_POST['RedeemModel']['introduction']);
            //赋值
            $objModel->attributes = $_POST['RedeemModel'];

            $position = MoneyPositionModel::model()->find('callback = :callback', array('callback' => 'redeemgood'));
            if (!$position) {
                $this->error('付款类型不存在', 'index');
            }

            if ($objModel->validate() && $objModel->save()) {
                Yii::import('ext.alipay.*');
                $alipay = new Alipay();

                $price = $objModel->quantum * $objModel->worth;
                $orders = array(
                    'type' => 0,
                    'uid' => Yii::app()->user->id,
                    'recommend_uid' => 0,
                    'order_title' => $position->title, //根据支付类型获取支付标题
                    'product_id' => $objModel->product_id,
                    'goods_name' => $objModel->title,
                    'price' => $objModel->worth, //商品价格
                    'money' => $price, //支付金额
                    'goods_bm_id' => $objModel->id,
                    'payment_types' => $position->id, //支付类型ID
                );

                if ($alipay->data($orders)->createOrders() !== true) {
                    $error = $alipay->getError();
                    $this->error($error ? $error : '订单创建失败，请重新提交！');
                }

                //跳转到支付宝支付页面
                //Yii::app()->user->setFlash( 'http', '/user/redeemgood/index' );
                //$this->setcookie(name)
                $url = $alipay->payment('', true);
                if ($url == false) {
                    $error = $alipay->getError();
                    $this->error($error ? $error : '订单处理错误！');
                } else {
                    $this->success('报名成功，马上前往支付页面！', $url);
                    exit;
                }

                //生成订单并付款							
                //$objModel->doPay($position);				
            }
        }

        $this->render('add', array('model' => $objModel));
    }

    /**
     * 商家的积分商品列表
     * @return [type] [description]
     */
    public function actionIndex() {
        $objModel = new RedeemModel('search');

        $objModel->resetAttributes();
        $label = isset($_GET['label']) ? $_GET['label'] : 0;
        $this->assign('label', $label);
        if (isset($_GET['RedeemModel'])) {
            $objModel->attributes = $_GET['RedeemModel'];
        }
        $count = $objModel->getLabelForList($label, yii::app()->user->id);
        $this->assign('count', $count);
        $objModel->uid = yii::app()->user->id;
        $objCriteria = $objModel->createSearchCriteria();

        $objPager = new CPagination($objModel->count($objCriteria));
        $objPager->pageSize = 10;
        $objPager->applyLimit($objCriteria);

        $objSort = new CSort('RedeemModel');
        $objSort->applyOrder($objCriteria);

        $objModels = $objModel->findAll($objCriteria);
        $this->assign('pages', $objPager);
        $this->assign('sort', $objSort);
        $this->assign('model', $objModel);
        $this->assign('models', $objModels);
        $this->render('index');
    }

    public function actionCancel() {
        $id = Yii::app()->request->getParam('id');

        $objModel = RedeemModel::model()->findByPk($id);
        if (!$objModel) {
            $this->error('找不到此记录');
        }
        //验证是否可以执行取消操作
        if ($objModel->canCancel()) {
            $objModel->status = RedeemModel::STATUS_CANCEL;

            //看是否有付款,有付款则改变状态准备进行退款
            if ($objModel->pay_status == RedeemModel::PAY_STATUS_HAS) {
                $objModel->pay_status = RedeemModel::PAY_STATUS_REFUND_NOT;
            }
            $objModel->save(true, array('status', 'pay_status'));

            $this->success('成功取消');
        } else {
            $this->error('不能执行取消操作');
        }
    }

    public function actionEdit() {
        $this->error('该功能已关闭');
        $id = Yii::app()->request->getParam('id');

        $objModel = RedeemModel::model()->findByPk($id);
        if (!$objModel) {
            $this->error('找不到此记录', 'index');
        }

        if (!$objModel->canUpdate()) {
            $this->error('不能执行修改操作', 'index');
        }

        $objModel->setScenario('edit');
        $objModel->start_time = empty($objModel->start_time) ? '' : date('Y-m-d H:i', $objModel->start_time);
        $objModel->end_time = empty($objModel->end_time) ? '' : date('Y-m-d H:i', $objModel->end_time);
        if (isset($_POST['RedeemModel'])) {
            //过滤Post数据
            $this->unsetPostData(array('status', 'admin_id', 'pay_status', 'product_id'));

            $_POST['RedeemModel']['introduction'] = CHtml::encode($_POST['RedeemModel']['introduction']);

            //赋值
            $objModel->attributes = $_POST['RedeemModel'];

            $position = MoneyPositionModel::model()->find('callback = :callback', array('callback' => 'redeemgood'));
            if (!$position) {
                $this->error('付款类型不存在', 'index');
            }

            if ($objModel->validate() && $objModel->save()) {

                //判断有无生成订单表，如果有生成则修改订单表的数据，如果没有生成则生成订单表

                Yii::import('ext.alipay.*');
                $alipay = new Alipay();

                $arrData = array(
                    'payment_types' => $position->id,
                    'goods_bm_id' => $objModel->id,
                );
                $objOrderModel = MoneyPositionOrderModel::model()->find('goods_bm_id = :goods_bm_id AND payment_types = :payment_types', $arrData);
                if ($objOrderModel) {
                    $objOrderModel->goods_name = $objModel->title;
                    $objOrderModel->price = $objModel->worth;
                    $objOrderModel->money = $objModel->worth * $objModel->quantum;
                    $objOrderModel->save(false, array('goods_name', 'price', 'money'));

                    $alipay->data($objOrderModel->attributes);
                    $ordersId = $objOrderModel;
                } else {
                    $price = $objModel->quantum * $objModel->worth;
                    $orders = array(
                        'type' => 0,
                        'uid' => Yii::app()->user->id,
                        'recommend_uid' => 0,
                        'order_title' => $position->title, //根据支付类型获取支付标题
                        'product_id' => $objModel->product_id,
                        'goods_name' => $objModel->title,
                        'price' => $objModel->worth, //商品价格
                        'money' => $price, //支付金额
                        'goods_bm_id' => $objModel->id,
                        'payment_types' => $position->id, //支付类型ID
                    );

                    if ($alipay->data($orders)->createOrders() !== true) {
                        $error = $alipay->getError();
                        $this->error($error ? $error : '订单创建失败，请重新提交！');
                    }
                    $ordersId = '';
                }

                //跳转到支付宝支付页面
                //Yii::app()->user->setFlash( 'http', '/user/redeemgood/index' );
                $url = $alipay->payment($ordersId, true);
                if ($url == false) {
                    $error = $alipay->getError();
                    $this->error($error ? $error : '订单处理错误！');
                } else {
                    $this->success('报名成功，马上前往支付页面！', $url);
                    exit;
                }
            } else {
                if (Yii::app()->request->isAjaxRequest) {
                    $error = $objModel->getOneError();
                    $this->error($error ? $error : '修改失败！');
                }
            }
        }

        $this->render('edit', array('model' => $objModel));
    }

    public function actionView() {
        $id = Yii::app()->request->getParam('id');

        $objModel = RedeemModel::model()->findByPk($id);

        if (!$objModel) {
            $this->error('找不到此记录', 'index');
        }

        $this->render('view', array('model' => $objModel));
    }

    public function actionPay() {
        $id = Yii::app()->request->getParam('id');

        $objModel = RedeemModel::model()->findByPk($id);
        if (!$objModel) {
            $this->error('找不到此记录', 'index');
        }

        $position = MoneyPositionModel::model()->find('callback = :callback', array('callback' => 'redeemgood'));
        if (!$position) {
            $this->error('付款类型不存在', 'index');
        }


        if ($objModel->pay_status == RedeemModel::PAY_STATUS_NOT) {

            Yii::import('ext.alipay.*');
            $alipay = new Alipay();

            $arrData = array(
                'payment_types' => $position->id,
                'goods_bm_id' => $objModel->id,
            );
            $objOrderModel = MoneyPositionOrderModel::model()->find('goods_bm_id = :goods_bm_id AND payment_types = :payment_types', $arrData);
            if ($objOrderModel) {
                $alipay->data($objOrderModel->attributes);
                $orderID = $objOrderModel;
            } else {
                $price = $objModel->quantum * $objModel->worth;
                $orders = array(
                    'type' => 0,
                    'uid' => Yii::app()->user->id,
                    'recommend_uid' => 0,
                    'order_title' => $position->title, //根据支付类型获取支付标题
                    'product_id' => $objModel->product_id,
                    'goods_name' => $objModel->title,
                    'price' => $objModel->worth, //商品价格
                    'money' => $price, //支付金额
                    'goods_bm_id' => $objModel->id,
                    'payment_types' => $position->id, //支付类型ID
                );

                if ($alipay->data($orders)->createOrders() !== true) {
                    $error = $alipay->getError();
                    $this->error($error ? $error : '订单创建失败，请重新提交！');
                }
                $orderID = '';
            }

            //跳转到支付宝支付页面

            $url = $alipay->payment($orderID, true);
            if ($url == false) {
                $error = $alipay->getError();
                $this->error($error ? $error : '订单处理错误！');
            } else {
                $this->success('报名成功，马上前往支付页面！', $url);
                exit;
            }
        } else {
            $this->error('已经付款', 'index');
        }
    }

    /**
     * 商家的商品的记录列表
     * @return [type] [description]
     */
    public function actionRecord() {
        $objModel = new RedeemRecordsModel('search');

        $objModel->resetAttributes();

        if (isset($_GET['RedeemRecordsModel'])) {
            $objModel->attributes = $_GET['RedeemRecordsModel'];
        }


        $objCriteria = $objModel->createSearchCriteria();
        $objCriteria->addCondition('RedeemModel.uid = ' . yii::app()->user->id);

        $intCount = $objModel->with('RedeemModel')->count($objCriteria);



        $objPager = new CPagination($intCount);
        $objPager->pageSize = 10;
        $objPager->applyLimit($objCriteria);

        $objSort = new CSort('RedeemRecordsModel');
        $objSort->defaultOrder = 't.id DESC';
        $objSort->applyOrder($objCriteria);


        $objModels = $objModel->with('RedeemModel')->findAll($objCriteria);

        $this->assign($_GET);
        $this->assign('pages', $objPager);
        $this->assign('sort', $objSort);
        $this->assign('model', $objModel);
        $this->assign('models', $objModels);
        $this->render('record');
    }

    public function actionSure() {
        $id = Yii::app()->request->getParam('id');
        $objModel = RedeemRecordsModel::model()->findByPk($id);

        if (!$objModel) {
            $this->error('找不到此记录');
        }
        
        if ($objModel->is_sure == RedeemRecordsModel::SURE_HAS) {
            $this->error('操作不正确');
        }

        if ($objModel->order_sn == '') {
            $this->error('买家还未填写订单号');
        }
        $objModel->is_sure = RedeemRecordsModel::SURE_HAS;
        $objModel->save(false, array('is_sure'));
        $this->success('成功确定');
    }


    //分享增加积分
    public function actionShare() {

        $goods_id = Yii::app()->request->getParam('goods_id');
        $uid = Yii::app()->user->id;
        $user = MembersModel::model()->findByPk($uid);
        if (empty($user)) {
            $this->error('获取用户信息失败！', self::U('user/login/login'));
        }
        $objGoodsModel = GoodsModel::model()->findByPk($goods_id);
        if (!$objGoodsModel) {
            $this->error('商品信息错误');
        }
        $key = "RedeemgoodController_Share_{$goods_id}_{$uid}";
        $cache = Yii::app()->cache->get($key);
        $time = time();
        $time_today = strtotime('today');

        if(empty($cache)){
            Yii::app()->cache->set($key, $time, $time_today + 86399 - $time);
        }else{
            if($cache > $time_today){ //今天分享过
                $this->error('今天已经分享过此商品');
            }else{//今天没有分享过
                Yii::app()->cache->set($key, $time, $time_today + 86399 - $time);
            }
        }

        //增加积分
        if (MembersModel::model()->plusScore($uid, 5) == true) {
            MembersActionModel::model()->addShareAction($uid, '分享送积分活动，赠送积分 5 。');
            //经验值
            MembersModel::model()->plusExp($uid, 1, '分享商品，经验值加1。');
            $this->success('增加分享积分成功！');
        } else {
            $this->error('积分增加失败！');
        }
    }    

}
